<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/17
 * Time: 17:02
 */

namespace app\admin\controller;
use app\admin\model\SpecialColumn;
use app\admin\model\SpecialContent as SpecialContentModel;

class SpecialContentController extends BaseController
{
    //专题栏目内容列表
    public function index()
    {
        $content = SpecialContentModel::all();
        $column = SpecialColumn::all();
        $this->assign([
           'content' => $content,
           'column' => $column,
        ]);
        return $this->fetch();
    }
    //添加
    public function add()
    {
        if ($this->request->isPost()){
            $param = $this->request->param();
            if ($this->request->file('img')){
                $uploadFile = uploadFile('img',50,50);
                $param['pic'] = $uploadFile['origin'];
                $param['sm_pic'] = $uploadFile['thumb'];
            }
            $model = new SpecialContentModel();
            $result = $model->validate(true)->allowField(true)->save($param);
            if ($result){
                $this->success('添加成功',url('SpecialContent/index'),'',2);
            }else{
                $this->error('添加失败'.$model->getError());
            }
        }
        $column = SpecialColumn::all();
        $this->assign('column',$column);
        return $this->fetch();
    }
    //修改
    public function edi()
    {
        $param = $this->request->param();
        if ($this->request->isPost()){
            if ($this->request->file('img')){
                $uploadFile = uploadFile('img',50,50);
                $param['pic'] = $uploadFile['origin'];
                $param['sm_pic'] = $uploadFile['thumb'];
                $oldFile = SpecialContentModel::field('pic,sm_pic')->find($param['id']);
                if ($oldFile['pic']){
                    uploadDelete([$oldFile->pic,$oldFile->sm_pic],1);
                }
            }
            $model = new SpecialContentModel();
            if ($model->validate(true)->allowField(true)->isUpdate(true)->save($param)){
                $this->success('修改成功',url('SpecialContent/index'),'',2);
            }
            $this->error('修改失败'.$model->getError());
        }
        $special = SpecialContentModel::find($param['id']);
        $column = SpecialColumn::all();
        $this->assign('special',$special);
        $this->assign('column',$column);
        return $this->fetch();
    }
    //删除
    public function del()
    {
        $id = $this->request->param('id');
        $oldFile = SpecialContentModel::field('pic,sm_pic')->find($id);
        if ($oldFile['pic']){
            uploadDelete([$oldFile->pic,$oldFile->sm_pic],1);
        }
        if (SpecialContentModel::where('id',$id)->delete()){
            return ['error'=>0,'msg'=>"删除成功"];
        }
        return ['error'=>1,'msg'=>"删除失败"];
    }
}